const express = require('express');
const router = express.Router();
const PracticeRecord = require('../models/practiceRecord');
const jwt = require('jsonwebtoken');

// 保存练习记录
router.post('/record', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const userId = decoded.id;

    const {
      practiceDate,
      totalProblems,
      correctCount,
      accuracy,
      totalTime,
      details
    } = req.body;

    const record = await PracticeRecord.create({
      userId,
      practiceDate,
      totalProblems,
      correctCount,
      accuracy,
      totalTime,
      details
    });

    res.json({
      success: true,
      message: '练习记录保存成功',
      data: record
    });
  } catch (error) {
    console.error('保存练习记录失败:', error);
    res.status(500).json({
      success: false,
      message: '保存练习记录失败'
    });
  }
});

// 获取用户的练习记录
router.get('/records', async (req, res) => {
  try {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
      return res.status(401).json({
        success: false,
        message: '未提供认证token'
      });
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const userId = decoded.id;

    const records = await PracticeRecord.findByUserId(userId);
    res.json({
      success: true,
      data: records
    });
  } catch (error) {
    console.error('获取练习记录失败:', error);
    res.status(500).json({
      success: false,
      message: '获取练习记录失败'
    });
  }
});

module.exports = router; 